package com.sds.servlet;


import com.google.common.collect.Maps;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.sds.ai.api.provider.ResponseProvider;
import com.sds.ai.impl.data.logging.ChatSession;
import com.sds.ai.impl.provider.AIMLResponseProvider;
import com.sds.ai.impl.provider.DataProviderImpl;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Singleton
public class ChatServlet extends HttpServlet {

    private final Logger LOGGER = Logger.getLogger(getClass());
    private final ResponseProvider responseProvider;
    private final Map<String, String> memory = Maps.newHashMap();
    private final SimpleDateFormat sdf = new SimpleDateFormat();
    private final Provider<ChatSession> session;
    private final DataProviderImpl dataProvider;
    private final AIMLResponseProvider aimlResponseProvider;

    @Inject
    public ChatServlet(ResponseProvider responseProvider, Provider<ChatSession> session, DataProviderImpl dataProvider, AIMLResponseProvider aimlResponseProvider) {
        this.responseProvider = responseProvider;
        this.session = session;
        this.dataProvider = dataProvider;
        this.aimlResponseProvider = aimlResponseProvider;
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Date currentTime = new Date();
        String userMessage = request.getParameter("message");
        String botMessage = responseProvider.getResponse(userMessage, memory).trim();
        botMessage = botMessage.trim().length() > 0 ? botMessage : aimlResponseProvider.getResponse(memory,userMessage).trim();

        ChatSession currentChatSession = dataProvider.getManagedInstance(session.get());
        if (currentChatSession.getStart() == null) {
            currentChatSession.setStart(currentTime);
        }
        currentChatSession.appendMessage("[" + sdf.format(currentTime) + "]GUEST:\t" + userMessage);
        currentChatSession.appendMessage("[" + sdf.format(new Date()) + "]BOT:\t" + botMessage);
        currentChatSession.setEnd(new Date());
        dataProvider.update(currentChatSession);

        response.getWriter().write(URLEncoder.encode(botMessage, "UTF-8").replaceAll("\\+", "%20"));

        LOGGER.info("SESSION[" + request.getSession().getId() + "]-USER:" + URLEncoder.encode(userMessage, "UTF-8"));
        LOGGER.info("SESSION[" + request.getSession().getId() + "]-BOT:" + URLEncoder.encode(botMessage, "UTF-8"));
    }
}
